package cn.lkp.mall.product.service.impl;

import cn.lkp.common.constant.ProductConstant;
import cn.lkp.mall.product.dao.AttrAttrgroupRelationDao;
import cn.lkp.mall.product.dao.AttrGroupDao;
import cn.lkp.mall.product.dao.CategoryDao;
import cn.lkp.mall.product.entity.AttrAttrgroupRelationEntity;
import cn.lkp.mall.product.entity.AttrGroupEntity;
import cn.lkp.mall.product.entity.CategoryEntity;
import cn.lkp.mall.product.service.CategoryService;
import cn.lkp.mall.product.vo.AttrGroupRelationVo;
import cn.lkp.mall.product.vo.AttrRespVo;
import cn.lkp.mall.product.vo.AttrVo;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.lkp.common.utils.PageUtils;
import cn.lkp.common.utils.Query;

import cn.lkp.mall.product.dao.AttrDao;
import cn.lkp.mall.product.entity.AttrEntity;
import cn.lkp.mall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }
    @Autowired
    AttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        /**
         * 逐一给attrEntity的字段赋值太麻烦，使用BeanUtils将vo属性拷贝到attrEntity
         * 要求实体类attrEntity和vo类attr拥有共同的字段名称。
         */
        //attrEntity.setAttrId(attr.getAttrId());
        BeanUtils.copyProperties(attr,attrEntity);
        //保存基本属性
        this.save(attrEntity);
        //保存关联关系
        if(attr.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId()!=null){
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            //AttrGroupId保存在vo中
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            //AttrId保存在po中
            relationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationDao.insert(relationEntity);
        }
    }
    @Autowired
    CategoryDao categoryDao;
    @Autowired
    AttrGroupDao attrGroupDao;
    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String attrType) {
        //不论catelog_id是否为0，都要拼attr_type
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type","base".equalsIgnoreCase(attrType)? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() :ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        if(catelogId !=0){
            queryWrapper.eq("catelog_id",catelogId);
        }
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            //attr_id attr_name
            queryWrapper.and((wrapper)->{
                wrapper.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        //pageUtils里面封装的数据不是AttrEntity，他里面的值是不够的，还要加上所属分类catelogName和所属分组groupName
        //得到page里面封装的AttrEntity列表
        List<AttrEntity> records = page.getRecords();
        //重新处理AttrEntity,映射里面的每一个AttrEntity元素
        List<AttrRespVo> respVos = records.stream().map((attrEntity) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            //属性对拷
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            //给所属分类catelogName赋值，注入categoryDao
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            //给所属分组groupName赋值
            //3.查单条关联关系得到AttrAttrgroupRelationEntity
            //如果查询的是base（基本属性）,才有分组信息
            if("base".equalsIgnoreCase(attrType)){
                AttrAttrgroupRelationEntity attr_id = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                if (attr_id != null && attr_id.getAttrGroupId()!=null) {
                    //4.得到attrGroupId
                    Long attrGroupId = attr_id.getAttrGroupId();
                    //2.需要在关系表attrAttrgroupRelation根据attr_id查attr_group_id，注入attrAttrgroupRelationDao
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
                    //1.需要在attrGroup中根据attr_group_id查attr_group_name，注入attrGroupDao
                    if(attrGroupEntity!=null){
                        attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    }
                }
            }
            return attrRespVo;
        }).collect(Collectors.toList());
        pageUtils.setList(respVos);
        return pageUtils;
    }
    @Autowired
    CategoryService categoryService;
    //每次远程服务都很费时，加入缓存，args[0]为第一个参数值
    @Cacheable(value = "attr",key = "'attrinfo:'+#root.args[0]")
    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrRespVo attrRespVo = new AttrRespVo();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity,attrRespVo);
        if(attrEntity.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            //要设置分组信息attrGroupId，传递过来的参数是attrId，可以从AttrAttrgroupRelation中根据attrId查到attrGroupId
            AttrAttrgroupRelationEntity attr_id = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if(attr_id!=null){
                Long attrGroupId = attr_id.getAttrGroupId();
                attrRespVo.setAttrGroupId(attrGroupId);
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
                if(attrGroupEntity!=null){
                    String attrGroupName = attrGroupEntity.getAttrGroupName();
                    //有了attrGroupId，使用attrGroupDao直接查询attrGroupName
                    attrRespVo.setGroupName(attrGroupName);
                }
            }
        }
        //1.当前实体类有自己的id，但这是不够的，我们要查对应分类的完整路径
        Long catelogId = attrEntity.getCatelogId();
        //3.我们之前在categoryservice中写过一个方法findCatelogPath,可以注入categoryservice
        Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        //2.设置分类的完整路径
        attrRespVo.setCatelogPath(catelogPath);

        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        //4.设置分类的名称
        if(categoryEntity!=null){
            attrRespVo.setCatelogName(categoryEntity.getName());
        }
        return attrRespVo;
    }
    @Transactional
    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);

        AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
        relationEntity.setAttrId(attr.getAttrId());
        relationEntity.setAttrGroupId(attr.getAttrGroupId());
        UpdateWrapper<AttrAttrgroupRelationEntity> wrapper = new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId());
        if(attrEntity.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            Integer count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if(count>0){
                //修改分组关联
                attrAttrgroupRelationDao.update(relationEntity,wrapper);
            }else {
                //之前分组关联未设置，现在新增分组关联
                attrAttrgroupRelationDao.insert(relationEntity);
            }
        }
    }

    /**
     * 根据分组id查找所有关联的基本属性
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        //页面只需取得属性名和可选值，选择使用实体类收集数据
        List<Long> attrIds = relationEntities.stream().map((attr) -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());
        Collection<AttrEntity> attrEntities = null;
        if(attrIds == null||attrIds.size() == 0){
            return null;
        }
        //程序执行到这里，说明attrIds里面有值
        attrEntities = this.listByIds(attrIds);
        return (List<AttrEntity>) attrEntities;
    }

    @Override
    public void deleteRelation(AttrGroupRelationVo[] vos) {
        //单次删除请求
        //attrAttrgroupRelationDao.delete(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", 1L).eq("attr_group_id", 1L));
        //批量删除
        //delete from pms_attr_attrgroup_relation where (attr_id=1 and attr_group_id=1) or (attr_id=2 and attr_group_id=2)
        List<AttrAttrgroupRelationEntity> entities = Arrays.asList(vos).stream().map((item) -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item,relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());
        attrAttrgroupRelationDao.deleteBatchRelation(entities);
    }

    /**
     * 获取当前分组没有关联的属性
     * @param attrgroupId
     * @param params
     * @return
     */

    @Override
    public PageUtils getNoRelationAttr(Long attrgroupId, Map<String, Object> params) {
        //1.当前分组只能关联所属分组的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        //2.当前分组只能关联别的分组没有引用的属性
        //2.1 当前分类下的其他分组
        List<AttrGroupEntity> group = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        //2.2 这些分组关联的属性
        List<Long> groupList = group.stream().map((item) -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());
        List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", groupList));
        List<Long> attrList = relationEntities.stream().map((item) -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        //2.3 从当前分类的所有属性中移除这些属性
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if(attrList!=null && attrList.size()>0){
            wrapper.notIn("attr_id",attrList);
        }
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and((w)->{
                w.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        PageUtils pageUtils = new PageUtils(page);
        return pageUtils;
    }

    @Override
    public List<Long> selectSearchAttrIds(List<Long> attrIds) {
        //SELECT attr_id FROM pms_attr WHERE attr_id IN ? AND search_type = 1
        return baseMapper.selectSearchAttrIds(attrIds);
    }
}